package com.old.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.old.dto.PostQueryDTO;
import com.old.entity.Post;
import com.old.mapper.PostMapper;
import com.old.mapper.UserMapper;
import com.old.result.PageBean;
import com.old.service.PostService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {

    private final PostMapper postMapper;
    private final ObjectMapper objectMapper;
    private final UserMapper userMapper;


    private void validateQueryParams(PostQueryDTO queryDTO) {
        if (queryDTO.getPageNo() < 1) queryDTO.setPageNo(1);
        if (queryDTO.getPageSize() < 1 || queryDTO.getPageSize() > 100) {
            queryDTO.setPageSize(10);
        }
    }


    @Override
    public Post createPost(Post post) {
        // 设置时间戳
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());
        post.setLikeMan("[]");
        postMapper.createPost(post);
        return post; // 由于使用了 @Options，post 对象会自动填充 id
    }

    @Override
    public Post getPostDetail(Integer id) throws JsonProcessingException {
        Post list_init=   postMapper.getPostDetail(id);
            Post post = list_init;
            // 解析参与人数
            ObjectMapper objectMapper = new ObjectMapper();
            // 解析为JsonNode对象
            if (post.getLikeMan() != null) {
                JsonNode jsonNode = objectMapper.readTree(post.getLikeMan());
                // 获取数组元素个数
                int elementCount = jsonNode.size();
                if (id != null){

                    // 将字符串转换为JSONArray  likeman="[47, 2]",    例如userid=4，现在是likeman中存在4，就直接true了 ，所以不能用contains方法
                    JSONArray jsonArray = JSON.parseArray(post.getLikeMan());

                    // 使用FastJSON内置方法检查元素是否存在
                    boolean isGood = jsonArray.contains(id);

                    // 设置帖子的状态
                    post.setIsgood(isGood);

                } else {
                    post.setIsgood(false);
                }
                post.setLikeMan(Integer.toString(elementCount));
            }


        return list_init ;
    }

    @Override
    public List<Post> findByAccountId(Integer accountId) {
        return postMapper.findByAccountId(accountId);
    }

    @Override
    public PageBean getPostListById(PostQueryDTO postQueryDTO) {
        //分页查询
        PageHelper.startPage(postQueryDTO.getPageNo(), postQueryDTO.getPageSize());
        Page<Post> page = postMapper.postListPage(postQueryDTO);

        long total = page.getTotal();
        List<Post> records = page.getResult();

        return new PageBean(total, records);
    }

    @Override
    @Transactional
    public void deletePost(Integer postId, Integer userId) {
        // 1. 查询帖子是否存在
        Post post = postMapper.checkPostExist(postId);
        if (post == null) {
            throw new RuntimeException("帖子不存在");
        }

        // 2. 检查当前用户是否有权限删除帖子
        if (userMapper.findByID(userId).getStatus().equals(0) || post.getAuthorId().equals(userId)) {
            // 3. 删除戏曲
            postMapper.deletePost(postId);
            log.info("{}用户删除帖子{}", userId, postId);
        } else {
            log.info("非作者/管理员");
            throw new RuntimeException("无权限删除");
        }

    }

    @Override
    public PageBean pageList(Integer pageNo, Integer pageSize, Integer sortBy, String searchTerms, Integer userId) throws JsonProcessingException {
        PageHelper.startPage(pageNo, pageSize);

//        Map<String, Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
        List<Post> list = postMapper.list(sortBy, searchTerms);
        Page<Post> p = (Page<Post>) list;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        List list_init = pageBean.getList();

        for (Object o : list_init) {
            Post post = (Post) o;

            // 解析参与人数
            ObjectMapper objectMapper = new ObjectMapper();
            // 解析为JsonNode对象
            if (post.getLikeMan() != null) {
                JsonNode jsonNode = objectMapper.readTree(post.getLikeMan());
                // 获取数组元素个数
                int elementCount = jsonNode.size();
                if (userId != null){

                // 将字符串转换为JSONArray  likeman="[47, 2]",    例如userid=4，现在是likeman中存在4，就直接true了 ，所以不能用contains方法
                JSONArray jsonArray = JSON.parseArray(post.getLikeMan());

                // 使用FastJSON内置方法检查元素是否存在
                boolean isGood = jsonArray.contains(userId);

                // 设置帖子的状态
                post.setIsgood(isGood);

                } else {
                    post.setIsgood(false);
                }
                post.setLikeMan(Integer.toString(elementCount));
            }
        }

        return new PageBean(p.getTotal(), list_init);
    }

    //批量删除帖子
    @Override
    @Transactional
    public void deletePostsByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) return;
        postMapper.batchDeleteByIds(ids);
    }

    //点赞

    public Integer likePost(Integer postId, Integer userId) {
        // 1. 获取当前点赞列表
        String likeManJson = postMapper.getLikeManByPostId(postId);
        List<Integer> likeManList = parseLikeManJson(likeManJson);

        // 2. 检查是否已点赞
        if (likeManList.contains(userId)) {
            //throw new RuntimeException("请勿重复点赞");

        }

        // 3. 添加用户ID到列表
        likeManList.add(userId);
        String newLikeManJson = toJsonString(likeManList);

        // 4. 更新数据库
        postMapper.updateLikeMan(postId, newLikeManJson);

        // 5. 返回最新点赞数
        return likeManList.size();

    }

    //取消点赞
    @Override
    @Transactional
    public Integer cancelLike(Integer postId, Integer userId) {
        // 1. 获取当前点赞列表
        String likeManJson = postMapper.getLikeManByPostId(postId);
        List<Integer> likeManList = parseLikeManJson(likeManJson);

        // 2. 检查是否未点赞
        if (!likeManList.contains(userId)) {
            throw new RuntimeException("未点赞，无法取消");
        }

        // 3. 移除用户ID
        likeManList.remove(userId);
        String newLikeManJson = toJsonString(likeManList);

        // 4. 更新数据库
        postMapper.updateLikeMan(postId, newLikeManJson);

        // 5. 返回最新点赞数
        return likeManList.size();
    }

    @Override
    //用于判定是否在点赞列表中
    public boolean isGood(Integer userId, Integer id) {
        // 1. 获取当前点赞列表
        String likeManJson = postMapper.getLikeManByPostId(id);
        List<Integer> likeManList = parseLikeManJson(likeManJson);

        return likeManList.contains(userId);
    }


    // JSON 解析工具方法
    private List<Integer> parseLikeManJson(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<Integer>>() {
            });
        } catch (JsonProcessingException e) {
            log.error("JSON解析失败", e);
            return new ArrayList<>();
        }
    }

    private String toJsonString(List<Integer> list) {
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败", e);
            return "[]";
        }
    }
}
